package myRealm;

import entity.UserEntity;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import service.serviceImpl.UserService;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by Administrator on 2018/4/8.
 */
public class MyRealm extends AuthorizingRealm{

    @Resource
    private UserService userService;

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Set<String> roles = new HashSet<String>();
        Set<String> permissions = new HashSet<String>();
        roles.add("admin");
        permissions.add("*");
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(permissions);
        return authorizationInfo;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = (String)token.getPrincipal();
        UserEntity userEntity = userService.getByUserName(userName);
        if(userEntity!=null){
            AuthenticationInfo authcInfo=new SimpleAuthenticationInfo(userEntity.getUserName(),userEntity.getPassword(),"xx");
            return authcInfo;
        }else{
            return null;
        }
    }
}
